from dataclasses import dataclass
from typing import Dict, List

from .data_source import SourceType


@dataclass
class AppConfig:
    """应用配置"""

    # 数据项定义
    fields: List[
        Dict[str, str]
    ]  # [{"name": "xx", "code": "xx", "description": "xx"}, ...]
    # ID字段列表
    id_fields: List[str]
    # 数据源1配置
    source1_type: SourceType
    source1_path: str
    source1_mapping: Dict[str, str]  # {"source_field": "target_field", ...}
    # 数据源2配置
    source2_type: SourceType
    source2_path: str
    source2_mapping: Dict[str, str]
    # 显示选项
    show_all: bool = False

    def to_dict(self) -> dict:
        """转换为字典"""
        return {
            "fields": self.fields,
            "id_fields": self.id_fields,
            "source1": {
                "type": self.source1_type.value if self.source1_type else None,
                "path": self.source1_path,
                "mapping": self.source1_mapping,
            },
            "source2": {
                "type": self.source2_type.value if self.source2_type else None,
                "path": self.source2_path,
                "mapping": self.source2_mapping,
            },
            "show_all": self.show_all,
        }

    @classmethod
    def from_dict(cls, data: dict) -> "AppConfig":
        """从字典创建实例"""
        return cls(
            fields=data.get("fields", []),
            id_fields=data.get("id_fields", []),
            source1_type=(
                SourceType(data["source1"]["type"])
                if data.get("source1", {}).get("type")
                else None
            ),
            source1_path=data.get("source1", {}).get("path", ""),
            source1_mapping=data.get("source1", {}).get("mapping", {}),
            source2_type=(
                SourceType(data["source2"]["type"])
                if data.get("source2", {}).get("type")
                else None
            ),
            source2_path=data.get("source2", {}).get("path", ""),
            source2_mapping=data.get("source2", {}).get("mapping", {}),
            show_all=data.get("show_all", False),
        )
